package org.example.exampreparationtreasure.service.impl;

import org.example.exampreparationtreasure.common.CommonResultStatus;
import org.example.exampreparationtreasure.exception.UserException;
import org.example.exampreparationtreasure.mapper.UserMapper;
import org.example.exampreparationtreasure.model.entity.User;
import org.example.exampreparationtreasure.service.UserService;
import org.example.exampreparationtreasure.util.JwtUtil;
import org.example.exampreparationtreasure.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceimpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean register(String username,String password,String role) {
        if(username == null || password == null)
        {
            throw new UserException(CommonResultStatus.UNAUTHORIZED,"用户名或密码不能为空");
        }

        if(role == null){
            throw new UserException(CommonResultStatus.UNAUTHORIZED,"角色不能为空");
        }

        if(userMapper.selectByUsername(username)!= null)
        {
            throw new UserException(CommonResultStatus.PARAM_ERROR,"用户已存在");
        }

        String Salt = MD5Util.generateSalt();
        User user = new User();
        user.setSalt(Salt);
        user.setUsername(username);

        String encryptedPassword = MD5Util.encrypt(password,Salt);
        user.setPassword(encryptedPassword);
        user.setRole(role);

        return userMapper.insert(user) > 0;

    }

    @Override
    public String login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if(username == null || password == null)
        {
            throw new UserException(CommonResultStatus.UNAUTHORIZED,"用户名或密码不能为空");
        }

        if(!MD5Util.verify(password,user.getSalt(),user.getPassword()))
        {
            throw new UserException(CommonResultStatus.UNAUTHORIZED,"密码错误");
        }

        return jwtUtil.generateToken(username,userMapper.selectByUsername(username).getId());
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.selectByUsername(username);
    }
}
